<template>
  <div>
    <a-modal
      :title="type ? '新增角色' : '编辑角色'"
      :visible="visible"
      :confirmLoading="confirmLoading"
      destroyOnClose
      @cancel="cancel"
      @ok="handleOk"
    >
      <a-form
        ref="ruleForm"
        :form="form"
        :label-col="{span:4}"
        :wrapper-col="{span:19}"
        layout="horizontal"
      >
        <a-form-item label="角色名称">
          <a-input
            id="roleName"
            v-decorator="['roleName',
              {
                initialValue:record.roleName,
                rules: [{ required: true,message:'角色名称不能为空' }]
              }
            ]"
            placeholder="请输入角色名称..."
            :maxLength="10"
          />
        </a-form-item>
        <a-form-item label="菜单权限">
          <div>
            <a-checkbox @change="allRoleOpenClose">展开/折叠</a-checkbox>
            <a-checkbox @change="allRole" :checked="defaultChecked">全选/全不选</a-checkbox>
          </div>
          <div style="border:1px solid #ddd; padding: 10px 0px">
            <a-spin tip="Loading..." :spinning="loading">
              <a-tree
                v-decorator="['permissionIds',{ initialValue: checkedKeys} ]"
                v-model="checkedKeys"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                @expand="onExpand"
                @select="onSelect"
              />
            </a-spin>
          </div>
        </a-form-item>
        <a-form-item label="备注">
          <a-input
            v-decorator="['remark',
              {
                initialValue:record.remark,
              }
            ]"
            placeholder="请输入备注..."
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import store from '@/store'
import { message } from 'ant-design-vue'
import { mapGetters } from 'vuex'
import { getAllIds, mapTree } from '@/utils/util'
import { roleDetail , addRole, updateRoleInfo} from '@/api/role-manage'

export default {
  name: 'roleManagementAddEdit',
  props: ['visible', 'record', 'type'],
  ...mapGetters(['userInfo','roles']),
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false, // loading
      confirmLoading: false,
      modalVisible: false,
      roleSelectList:[],

      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],

      defaultChecked:false,

      allTreeData: getAllIds(store.getters.rolesAll, []), // 全部菜单权限
      treeData: store.getters.rolesAll.map((org) => mapTree(org))
    }
  },
  watch: {
    visible(val) {
      this.modalVisible = val;
      if(val && !this.type){
        this.roleDetail();
      } else {
        this.checkedKeys = [];
        this.selectedKeys = [];
        this.defaultChecked = false;
      }
      // this.checkedKeys = this.record;
    },
    checkedKeys(val) {
      // console.log('onCheck', val);
      if(val.length === this.allTreeData.length) {
        this.defaultChecked = true;
      } else {
        this.defaultChecked = false;
      }
    },
  },
  methods: {
    // 查询所有菜单权限
    roleDetail(){
      const params = {
        roleId: this.record.roleId,
        userId: store.getters.userInfo?.userId,
        uuid: this.record.uuid
      }
      this.loading = true;
      roleDetail(params).then(res => {
        this.loading = false;
        if(res.code === 200) {
          if(res.data.menuIdList && res.data.menuIdList.length) {
            this.checkedKeys = res.data.menuIdList;
            if(this.checkedKeys.length === this.allTreeData.length) {
              this.defaultChecked = true;
            } else {
              this.defaultChecked = false;
            }
          }
        }
      })
    },
    allRoleOpenClose(e){
      if(e.target.checked) {
        this.expandedKeys = this.allTreeData;
      } else {
        this.expandedKeys = []
      }
    },
    allRole(e){
      this.defaultChecked = !this.defaultChecked;
      if(e.target.checked) {
        this.checkedKeys = this.allTreeData;
        this.selectedKeys = this.allTreeData;
      } else {
        this.checkedKeys = [];
        this.selectedKeys = [];
      }
    },
    onExpand(expandedKeys) {
      // console.log('onExpand', expandedKeys);
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      // console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      // console.log('onSelect', info);
      this.selectedKeys = selectedKeys;
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          const params = {
           ...values,
            userId: store.getters.userInfo?.userId,
            permissionIds: this.checkedKeys,
          }
          // 如果是修改需要新增这两个参数
          if (!this.type) {
            params.roleId = this.record.roleId;
          }
          let api = this.type ? addRole : updateRoleInfo
          api(params).then(res => {
            this.confirmLoading = false
            if (res.code === 200) {
              message.success(res.msg || '操作成功！')
              this.$emit('onOk', this.type ? 'add' : 'edit')
            }
          })
        }
      })
    },
    cancel() {
      this.resetFormValue()
      this.$emit('cancel')
    },
    // 重置表单一般在第一次访问表单时进行重置
    resetFormValue() {
      this.$nextTick(() => {
        this.form.resetFields()
      })
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .ant-tree li{
  padding: 0px 0px !important;
}
</style>